package com.ruoyi.web.wx;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.CopyUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.wx.domain.dto.WxClassDTO;
import com.ruoyi.wx.domain.dto.WxUserDTO;
import com.ruoyi.wx.domain.from.WxUserFrom;
import com.ruoyi.wx.domain.vo.WxUserVO;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author 莫修
 * @date 2021/11/13
 */

@RestController
@RequestMapping("/wx/user")
public class WxUserApi {
	@Autowired
	private SysLoginService loginService;

	@Autowired
	private TokenService tokenService;

	@Autowired
	private SysPermissionService permissionService;

	@Autowired
	private ISysUserService sysUserService;

	@Autowired
	private ISysDeptService sysDeptService;



	@GetMapping("/login")
	@ApiOperation("微信登录")
	public AjaxResult login(String code) {
		if (code == null) {
			return AjaxResult.error("code不能为空");
		}
		return loginService.wxlogin(code);
	}

	/**
	 * 获取用户信息
	 *
	 * @return 用户信息
	 */
	@GetMapping("getInfo")
	@ApiOperation("获取当前微信登录用户信息")
	public AjaxResult getInfo(Long userId) {
		if (userId == null) {
			return AjaxResult.error("userId 不能为空");
		}
		SysUser user = sysUserService.selectUserById(userId);
		// 角色集合
		Set<String> roles = permissionService.getRolePermission(user);
		final WxUserDTO wxUserDTO = CopyUtil.copyObject(user, WxUserDTO.class);
		if (user.getDeptId() != null){
			WxClassDTO wxClassDTO = sysDeptService.selectClassDept(user.getDeptId());
			wxUserDTO.setWxClassDTO(wxClassDTO);
		}
		Map<String, Object> ajax = new HashMap<>(2);
		ajax.put("user", wxUserDTO);
		ajax.put("roles", roles);
		return AjaxResult.success(ajax);
	}

	/**
	 * 修改用户信息
	 *
	 * @return 用户信息
	 */
	@PostMapping("update")
	@ApiOperation("修改用户信息")
	public AjaxResult updateUser(@RequestBody WxUserFrom wxUserFrom) {
		int i = sysUserService.updateWxUser(wxUserFrom);
		return i == 0 ? AjaxResult.error("修改失败") : AjaxResult.success("修改成功");
	}

}
